package com.quanquan.store.controller;

import com.quanquan.store.dto.BuyingDTO;
import com.quanquan.store.dto.GroupBuyingDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.entity.GroupBuying;
import com.quanquan.store.request.GroupBuyingRequestBody;
import com.quanquan.store.service.GroupBuyingService;
import com.quanquan.store.service.GroupBuyingTradingRecordService;
import enums.ResCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import utils.StringUtil;
import web.response.ResultBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/group_buy")
public class GroupBuyingController {


    private static final String GROUP_NUM = "groupNum_";
    private static final String STRING = "_";
    public static final String MONEY = "money";

    private final RestTemplate restTemplate;

    private final GroupBuyingService groupBuyingService;

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GroupBuyingTradingRecordService groupBuyingTradingRecordService;

    public GroupBuyingController(RestTemplate restTemplate, GroupBuyingService groupBuyingService, StringRedisTemplate stringRedisTemplate) {
        this.restTemplate = restTemplate;
        this.groupBuyingService = groupBuyingService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 管理端创建商城团购商品
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultBody createGroupBuying(@RequestBody GroupBuyingRequestBody requestBody) {
        String shoppingKill = groupBuyingService.createGroupBuying(requestBody);
        if (shoppingKill == null) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "团购商品创建失败");
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), com.alibaba.fastjson.JSONObject.toJSON(shoppingKill));

    }


    /**
     * 管理端查询所有团购商品
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> findAllGropingBuying(GroupBuyingRequestBody requestBody) {

        Integer page = requestBody.getPage();
        if (null != page && page > 0) {
            page = page - 1;
            requestBody.setPage(page);
        }
        BuyingDTO killDTO = groupBuyingService.queryAllShoppingKill(requestBody);
        Map<String, Object> data = new HashMap<>();
        if (null != killDTO) {
            data.put("size", killDTO.getSize());
            data.put("rows", killDTO.getGroupBuyingList());
            data.put("status", 200);
            data.put("msg", "success!");
            data.put("total", killDTO.getTotal());
        } else {
            data.put("size", 10);
            data.put("rows", null);
            data.put("status", -200);
            data.put("msg", "no data!");
            data.put("total", 0);
        }
        return data;
    }


    /**
     * 前端查询所有团购商品
     *
     * @return
     */
    @PostMapping("/query_web")
    @ResponseBody
    public ResultBody findAllGroupBuyingWeb(@RequestBody GroupBuyingRequestBody requestBody) {

        Integer page = requestBody.getPage() == null ? 0 : requestBody.getPage();
        Integer size = requestBody.getSize() == null ? 100 : requestBody.getSize();

        String killStatus = requestBody.getKillStatus();


        List<GroupBuying> groupBuyings = groupBuyingService.queryAllGroupBuyingWeb(page, size, killStatus);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), com.alibaba.fastjson.JSONObject.toJSON(groupBuyings));

    }


    /**
     * 前端查询秒杀活动详情
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResultBody findGroupBuyingDetails(@RequestBody GroupBuyingRequestBody requestBody) {
        String groupBuyingId = requestBody.getGroupBuyingId();
        GroupBuyingDTO groupBuyingDTO = groupBuyingService.queryGroupBuyingDetails(groupBuyingId);
        if (groupBuyingDTO == null) {
            return new ResultBody(ResCodeEnum.SHOPPINGKILL_OVER.getCode(), ResCodeEnum.SHOPPINGKILL_OVER.getMsg(), groupBuyingDTO);

        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), groupBuyingDTO);

    }


    /**
     * 后端端查询秒杀活动详情
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/edit_management")
    @ResponseBody
    public ResultBody findGroupBuyingDetailsManagement(@RequestBody GroupBuyingRequestBody requestBody) {
        String groupBuyingId = requestBody.getGroupBuyingId();
        GroupBuyingDTO groupBuyingDTO = groupBuyingService.queryGroupBuyingDetailsManagement(groupBuyingId);
        if (groupBuyingDTO == null) {
            return new ResultBody(ResCodeEnum.SHOPPINGKILL_OVER.getCode(), ResCodeEnum.SHOPPINGKILL_OVER.getMsg(), groupBuyingDTO);

        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), groupBuyingDTO);

    }

    //上下加要处理缓存
    @PostMapping("/update")
    @ResponseBody
    public ResultBody updateShoppingKill(@RequestBody GroupBuyingRequestBody requestBody) {

        String msg = groupBuyingService.updateGroupBuying(requestBody);
        if (StringUtil.isEmpty(msg)) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "团购商品修改失败");

        }
        System.out.println("msg...." + msg);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), msg);

    }


    @PostMapping("/put_away")
    @ResponseBody
    public ResultBody putAway(String id) {
        GroupBuying groupBuying = groupBuyingService.groupBuyingDetails(id);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), groupBuying);
    }


    /**
     * 用户点击抢购按钮
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/click")
    @ResponseBody
    public ResultBody participateGroupBuying(@RequestBody GroupBuyingRequestBody requestBody) {


        String groupBuyingId = requestBody.getGroupBuyingId();

        //判断是否可以点击
        //用户的id
        //秒杀商品的id
        //点击进入的时间(自己生成)
        //只要进到这里返回redis 里的值减掉1
        String userId = requestBody.getUserId();
        String openId = requestBody.getOpenId();


        GroupBuying groupBuying = groupBuyingService.getGroupBuying(groupBuyingId);

        //判断是否会已下单并且支付完成
        //判断用户是否支付完毕读取redis
        String uuid = stringRedisTemplate.opsForValue().get(GROUP_NUM + groupBuyingId + STRING + userId);
        if (StringUtil.isNotEmpty(uuid)) {

            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("uuid", uuid);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectHashMap);

        }
        //查询订单表是否下过单

        Boolean result = groupBuyingTradingRecordService.checkTimes(userId, groupBuyingId);
        if (!result) {
            return new ResultBody(ResCodeEnum.SHOPPINGKILL_COUNT.getCode(), "你已参加请勿重复参加", "你已参加请勿重复参加");
        }


        if (result) {
            Long decr = groupBuyingService.decr(groupBuyingId);
            System.out.println("decr:......." + decr);
            String payType = groupBuying.getPayType();
            if (decr < 0L) {
                groupBuyingService.incr(groupBuyingId);
                return new ResultBody(ResCodeEnum.SHOPPINGKILL_FINISH.getCode(), ResCodeEnum.SHOPPINGKILL_FINISH.getMsg(), "商品已抢完");
            }
            if (payType.equals(MONEY)) {
                //根据id查询缓存当缓存数变为0时返回已抢完
                //返回支付页面
                Map<String, Object> stringObjectMap = groupBuyingService.createshoppingRecord(userId, groupBuying, openId);

                if (stringObjectMap == null) {
                    groupBuyingService.incr(groupBuyingId);
                    return new ResultBody(ResCodeEnum.SHOPPINGKILL_ERROR.getCode(), ResCodeEnum.SHOPPINGKILL_ERROR.getMsg());

                }
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectMap);
            }

            //校验用户积分是否能够支付
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(userId);
            idDTO.setIntegral(groupBuying.getIntegral());
            Boolean aBoolean = restTemplate.postForObject("http://QUANQUAN-USER/user/check_balance", idDTO, Boolean.class);
            if (aBoolean) {

                //根据id查询缓存当缓存数变为0时返回已抢完
                //返回支付页面
                Map<String, Object> stringObjectMap = groupBuyingService.createshoppingRecord(userId, groupBuying, openId);

                if (stringObjectMap == null) {
                    groupBuyingService.incr(groupBuyingId);
                    return new ResultBody(ResCodeEnum.SHOPPINGKILL_ERROR.getCode(), ResCodeEnum.SHOPPINGKILL_ERROR.getMsg());

                }
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectMap);
            } else {
                groupBuyingService.incr(groupBuyingId);
                return new ResultBody(ResCodeEnum.INTEGRAL_DEFICIENCY.getCode(), ResCodeEnum.INTEGRAL_DEFICIENCY.getMsg(), "用户积分不足");
            }
        }

        return new ResultBody(ResCodeEnum.SHOPPINGKILL_COUNT.getCode(), ResCodeEnum.SHOPPINGKILL_COUNT.getMsg(), "用户无法秒杀");

    }



}
